package com.yhsimon.rabbitmq.topics;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    private static Runnable runnable=new Runnable() {
        @Override
        public void run() {
            //1. 创建连接工厂
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("192.168.100.128");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            connectionFactory.setVirtualHost("/");

            //获取队列的名称
            final String queueName = Thread.currentThread().getName();
            Connection connection=null;
            Channel channel=null;
            try {
                // 创建连接Connection
                connection= connectionFactory.newConnection("消费者");
                // 通过连接获取通道Channel
                channel = connection.createChannel();
                //这里如果queue已经被创建过一次，可以不需要定义
                //channel.queueDeclare("queue1",false,false,false,null);

                Channel finalChannel=channel;
                finalChannel.basicConsume(queueName, true, new DeliverCallback() {
                    @Override
                    public void handle(String consumerTag, Delivery message) throws IOException {
                        System.out.println(message.getEnvelope().getDeliveryTag());
                        System.out.println(queueName+"收到的消息是" + new String(message.getBody(),"UTF-8"));
                    }
                }, new CancelCallback() {
                    @Override
                    public void handle(String consumerTag) throws IOException {
                        System.out.println("接收失败了...");
                    }
                });

                System.out.println(queueName+"开始接收消息");
                System.in.read();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //7. 关闭通道
                if(channel!=null&&channel.isOpen()){
                    try {
                        channel.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //8. 关闭连接
                if(connection!=null&&connection.isOpen()){
                    try {
                        connection.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };


    public static void main(String[] args) {
        new Thread(runnable,"queue1").start();
        new Thread(runnable,"queue2").start();
        new Thread(runnable,"queue3").start();
    }
}
